package com.qire.common.concurrent;

import com.qire.common.basic.ObjectUtil;
import com.qire.common.function.TaskAction;

/**
 * 程序工人
 * @param <T> 处理数据类型
 */
public class Worker<T> implements TaskAction<T> {

    /** 处理程序 */
    private final TaskAction<T> taskAction;
    /** 调度器 */
    private final Scheduler scheduler;

    Worker(TaskAction<T> taskAction, Scheduler scheduler) {
        this.taskAction = taskAction;
        this.scheduler = scheduler;
    }

    @Override
    public void accept(T data) {
        if(ObjectUtil.isNull(scheduler) || scheduler.isSync()) {
            taskAction.accept(data);
        } else {
            scheduler.scheduler(taskAction, data);
            taskAction.waitNext();
        }
    }

    public Worker<T> andThen(Worker<T> after) {
        return new Worker<T>(data -> { taskAction.accept(data); after.accept(data); }, scheduler);
    }

}
